package com.zjinyin.forum.controller;

import com.sun.istack.internal.NotNull;
import com.zjinyin.forum.common.AppResult;
import com.zjinyin.forum.common.ResultCode;
import com.zjinyin.forum.config.AppConfig;
import com.zjinyin.forum.model.Article;
import com.zjinyin.forum.model.Board;
import com.zjinyin.forum.model.User;
import com.zjinyin.forum.service.IArticleService;
import com.zjinyin.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-08-10
 * Time: 17:02
 */
@Api(tags = "帖子相关接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IBoardService boardService;

    @Resource
    private IArticleService articleService;

    /**
     * 用户发布帖子 - 发布到那个版块下
     *
     * @param boardId 版块 Id
     * @param title   帖子标题
     * @param content 帖子正文
     * @param request 请求
     * @return 返回是否创建成功
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult createArticle(@ApiParam("版块 Id") @RequestParam("boardId") @NonNull Long boardId,
                                   @ApiParam("帖子标题") @RequestParam("title") @NotNull String title,
                                   @ApiParam("帖子正文") @RequestParam("content") @NotNull String content,
                                   HttpServletRequest request) {
        // 1. 判断用户是否禁用
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 2. 对 boardId 的版块进行校验
        Board board = boardService.selectById(boardId);
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            // board 不存在 或者版块状态异常 或者当前版块已经被删除
            log.warn(ResultCode.FAILED_BOARD_ABNORMAL.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_ABNORMAL);
        }
        // 3. 封装文章对象
        Article article = new Article();
        // 设置标题
        article.setTitle(title);
        // 设置振文
        article.setContent(content);
        // 设置版块
        article.setBoardId(boardId);
        // 设置文章归属用户
        article.setUserId(user.getId());

        // 4. 写入数据库
        articleService.create(article);
        return AppResult.success();
    }

    /**
     * 获取版块下对应文章数
     *
     * @param boardId 版块 Id
     * @return 返回版块下的文章
     */
    @ApiOperation("获取首页未删除的所有帖子或者指定版块帖子")
    @GetMapping("/getAllBoardArticle")
    public AppResult<List<Article>> getAllBoardArticle(@ApiParam("版块 Id")
                                                       @RequestParam(value = "boardId", required = false) Long boardId) {

        List<Article> list = null;
        // 1. 检验 boardId 是否传入
        if (boardId == null) {
            list = articleService.selectAll();
        } else {
            list = articleService.selectArticleByBoardId(boardId);
        }

        // 检验 list 结果
        if (list == null) {
            // 如果不进行 new 一个集合, 序列化后传入就是一个 null
            // new 以后传入的就是一个 [] 标准 js 的空集合
            list = new ArrayList<>();
        }
        return AppResult.success(list);
    }

    /**
     * 查询指定 id 的帖子
     *
     * @param id 帖子 id
     * @return 返回帖子对象
     */
    @ApiOperation("根据 ArticleId 查询指定的帖子")
    @GetMapping("/detailArticle")
    public AppResult getDetailArticleByArticleId(@ApiParam("帖子 Id") @RequestParam("id") @NotNull Long id,
                                                 HttpServletRequest request) {
        // 1. 获取 session
        HttpSession session = request.getSession(false);

        // 2. 获取当前登陆用户对象
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 3. 根据 id 获取指定文章
        Article article = articleService.selectArticleByABoardIdAndAId(id);

        // 4. 检验 article 对象
        if (article == null) {
            // log.warn("ArticleId : " + id + " " +ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 5. 检验文章对象的 UserId 是否为当前 user 的 id
        if (article.getUserId() == user.getId()) {
            // 将当前点击的文章标记为当前登陆用户的文章
            article.setOwn(true);
        }

        return AppResult.success(article);
    }


    /**
     * 修改指定 id 的帖子
     *
     * @param id      帖子 id
     * @param title   帖子标题
     * @param content 帖子正文
     * @param request 请求
     */
    @ApiOperation("修改指定 id 的帖子")
    @PostMapping("/modify")
    public AppResult modify(@ApiParam("帖子 id") @RequestParam("id") @NotNull Long id,
                            @ApiParam("文章标题") @RequestParam("title") @NotNull String title,
                            @ApiParam("文章正文") @RequestParam("content") @NonNull String content,
                            HttpServletRequest request) {
        // 1. 获取 session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 2. 检验用户状态是否正常  -- 被禁言或者当前用户已经注销了( 此操作可不判断 )
        if (user.getState() == 1) {
            log.warn("user : " + user.getUsername() + ", " + ResultCode.FAILED_USER_BANNED);
        }

        // 根据文章 id 查询帖子
        Article article = articleService.selectById(id);
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 3. 判断是否为作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        // 帖子已经删除了
        if (article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_ABNORMAL);
        }

        if (article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 4. 更新帖子
        articleService.modify(id, title, content);
        log.info("帖子已经重新编辑成功");

        return AppResult.success();
    }

    /**
     * 点赞功能, 更新点赞数
     *
     * @param id      文章 id
     * @param request 请求
     */
    @ApiOperation("更新点赞数")
    @PostMapping("/chickLikeCount")
    public AppResult chickLikeCount(@ApiParam("帖子 id") @RequestParam("id") @NotNull Long id,
                                    HttpServletRequest request) {
        // 1. 获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 2. 判断当前用户是否禁言, 禁言禁止更新操作
        if (user.getState() == 1) {
            log.warn("userId : " + id + ", " + ResultCode.FAILED_USER_BANNED);
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        articleService.chickLikeCount(id);
        return AppResult.success();
    }


    /**
     * 删除指定帖子
     *
     * @param id 帖子 id
     */
    @ApiOperation("删除指定帖子")
    @PostMapping("/deleteById")
    public AppResult deleteById(@ApiParam("帖子 id") @RequestParam("id") @NotNull Long id,
                                HttpServletRequest request) {
        // 1. 获取当前登陆用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 2. 校验用户状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 3. 根据 id 查询帖子
        Article article = articleService.selectById(id);

        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }

        if (article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 4. 检验是否为当前文章作者
        if (!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }

        articleService.deleteById(id);

        return AppResult.success();
    }


    /**
     * 根据用户 id 多表查询指定用户的未删除的所有文章
     *
     * @param userId 用户 id
     */
    @ApiOperation("多表查询指定用户所有为删除文章")
    @GetMapping("/selectArticleByUserId")
    public AppResult selectArticleByUserId(HttpServletRequest request,
                                           @ApiParam("用户 id") @RequestParam(value = "userId", required = false) Long userId) {

        // 不传入参数按照当前登陆用户 id 查询
        if (userId == null) {
            // 1. 获取当前用户
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }

        List<Article> list = articleService.selectArticleByUserId(userId);

        return AppResult.success(list);
    }


    /**
     * 根据文章标题关键字模糊匹配文章
     *
     * @param title 文章标题关键字
     * @return
     */
    @ApiOperation("关键字检索文章")
    @PostMapping("/selectParam")
    public AppResult selectAllArticleByTitle(@ApiParam("按照标题搜索") @RequestParam("title") @NotNull String title) {
        List<Article> list = articleService.selectAllArticleByTitle(title);
        return AppResult.success(list);
    }

}
